#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

LIBAV_VER=9.10

export PATH=$TOP_DIR/cross/bin:$PATH

# export MAKE_OPT="-j 2"

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -d libav-$LIBAV_VER ] ; then
		rm -rf libav-*
		wget http://www.libav.org/releases/libav-$LIBAV_VER.tar.gz
		tar xzf libav-$LIBAV_VER.tar.gz
	fi
	cd ..
fi


if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	ARCH_FLAG="--arch=x86_64"
	CROSS_PREFIX="x86_64-w64-mingw32-"
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		ARCH_FLAG="--arch=i686"
		CROSS_PREFIX="i686-w64-mingw32-"
	fi
	rm -rf $BIN_DIR/libav
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_libav
	mkdir bd_libav
	cd bd_libav
	export CPPFLAGS="-I$BIN_DIR/mingw_dgn_lib/include -I$BIN_DIR/xvid/include -I$BIN_DIR/x264/include -I$BIN_DIR/lame/include -I$BIN_DIR/opencoreamr/include -I$BIN_DIR/xavs/include"
	export LDFLAGS="-L$BIN_DIR/mingw_dgn_lib/lib -L$BIN_DIR/xvid/lib -L$BIN_DIR/x264/lib -L$BIN_DIR/lame/lib -L$BIN_DIR/opencoreamr/lib -L$BIN_DIR/xavs/lib"
	$SRC_DIR/libav-$LIBAV_VER/configure --prefix=$BIN_DIR/libav \
		--cross-prefix=$CROSS_PREFIX  \
		--target-os=mingw32 $ARCH_FLAG \
		--enable-w32threads \
		--enable-memalign-hack --disable-devices \
		--enable-gpl --enable-version3 \
		--enable-libxvid \
		--enable-libx264 \
		--enable-libmp3lame \
		--enable-libopencore-amrnb --enable-libopencore-amrwb \
		--enable-libvo-aacenc --enable-libvo-amrwbenc \
		--enable-libxavs \
		--disable-dxva2 \
		--enable-shared --disable-static

#		--disable-stripping --enable-debug
#	--enable-shared --disable-static \

	make $MAKE_OPT
	make install
	cd ..
	cd ..
fi

